/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.common.data.beetl.service.impl

import com.gitee.minimalismstyle.fresh.common.core.domain.QueryBody
import com.gitee.minimalismstyle.fresh.common.core.domain.QueryParams
import com.gitee.minimalismstyle.fresh.common.core.domain.R
import com.gitee.minimalismstyle.fresh.common.core.domain.Simple
import com.gitee.minimalismstyle.fresh.common.core.extra.genericTypeFirst
import com.gitee.minimalismstyle.fresh.common.data.commons.service.BaseService
import com.gitee.minimalismstyle.fresh.common.data.beetl.dao.BaseDao
import com.gitee.minimalismstyle.fresh.common.data.commons.annotation.Unique
import org.apache.commons.lang3.reflect.FieldUtils
import org.beetl.sql.annotation.entity.AssignID
import org.beetl.sql.clazz.kit.StringKit
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.transaction.annotation.Transactional

/**
 * jdbc 基础service
 * @author maoxiaodong
 */
abstract class BaseServiceImpl<DAO : BaseDao<T, ID>, T, ID> : BaseService<T, ID> {

    @Autowired
    protected lateinit var dao: DAO

    override fun findById(id: ID): R<T> = R.success(dao.findById(id))

    override fun findByIds(ids: List<ID>): R<List<T>> = R.success(dao.findAllById(ids))

    override fun findAll(): R<List<T>> = R.success(dao.findAll())

    @Transactional
    override fun save(t: T): R<T> {
        val uniqueR = isUnique(t)
        return if(uniqueR.get()){
            val count = dao.save(t)
            if(count> 0){
                R.success(t)
            }else{
                R.error("没有更新数据,数据已更新或删除", t)
            }
        }else{
            R.error(uniqueR.message!!, t)
        }

    }

    override fun saveAll(ts: List<T>): R<List<T>> {
        dao.saveAll(ts)
        return R.success(ts)
    }

    @Transactional
    override fun deleteById(id: ID): R<Int> {
        dao.deleteById(id)
        return R.success()
    }

    override fun deleteByIds(ids: List<ID>): R<Int> {
        return R.success(dao.deleteAllById(ids))
    }


    override fun isUnique(t: T): R<Boolean> {
        val entityClass = this.genericTypeFirst<T>(1)
        val fields = entityClass!!.declaredFields.filter { it.isAnnotationPresent(Unique::class.java) }
        return if(fields.isEmpty()){
            R.success(true)
        }else{
            val query = dao.createLambdaQuery()
            fields.forEach {
                val value = FieldUtils.readField(it, t, true)
                query.andEq(StringKit.enCodeUnderlined(it.name), value)
            }
            val classDesc = dao.getSQLManager().getClassDesc(entityClass)
            classDesc.idCols.forEach { idName ->
                val id = FieldUtils.readField(t, idName, true)
                if(id != null){
                    query.andNotEq(StringKit.enCodeUnderlined(idName), id)
                }
            }

            val count = query.count()
            if(count > 0){
                val values = fields.map { it.getAnnotation(Unique::class.java).value }
                R.success("${values.joinToString(",")}已存在",false)
            }else{
                R.success(true)
            }
        }

    }

    override fun findByQueryParams(params: QueryParams<Simple>): R<QueryBody<Simple>> {
        return R.success(dao.findByQueryParams(params))
    }
}
